package thesis.filesharing.web.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import thesis.filesharing.bo.StudentBO;
import thesis.filesharing.model.Student;
import thesis.filesharing.web.auth.AuthUtil;
import thesis.filesharing.web.viewmodel.ChangePasswordViewModel;

public class StudentChangePasswordValidator implements Validator {
	
	@Autowired
	private StudentBO studentBO;
	
	@Override
	public boolean supports(Class<?> clazz) {
		return ChangePasswordViewModel.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "oldPassword", "oldPassword.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "newPassword", "newPassword.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword", "confirmPassword.required");
		
		ChangePasswordViewModel model = (ChangePasswordViewModel) target;
		if (model.getNewPassword() != null && model.getNewPassword().length() > 0 &&
				model.getConfirmPassword() != null && model.getConfirmPassword().length() > 0 &&
				!model.getNewPassword().equals(model.getConfirmPassword())) {
			errors.reject("passwords.mismatch");
		}
		
		if (!errors.hasErrors()) {
			String studentId = AuthUtil.getCurrentAuthenticatedUsername();
			Student s = studentBO.findStudentById(studentId);
			if (s == null || (s != null && !model.getOldPassword().equals(s.getStudentPassword()))) {
				errors.reject("oldPassword.incorrect");
			}
		}
	}
}
